@echo off

@if "%1"=="" (
   @echo usage: %~n0 {certificate's subject name} {extra store name}
   @echo Example: %~n0 localhost root
   @echo Example: %~n0 localhost trustedpeople
   @goto :end
)

set SUBJECT=
for /f "tokens=* usebackq" %%i in (`certutil -v -store my ^| findstr /c:%1`) do (
	set SUBJECT=%%i
	goto :foundsubject
)

:foundsubject

set CERTHASH=

call "%~dp0SetCertHashFromSubjectName.bat" %1

for %%j in (%SUBJECT%) do (
	if %%j==%1 (
		echo.
		echo WARNING: A certificate with the subject %SUBJECT% is already present. 
		echo The sample might fail if there are two certificates with the same subject.
		echo Do you want to install the certificate anyway?
		choice
		echo.
		if ERRORLEVEL 2 goto :end
	)
)

@if NOT "%CERTHASH%" =="" (
  goto :doneHash
)

"%~dp0makecert.exe" -r -pe -a sha1 -n CN=%1 -sr LocalMachine -ss My -sky exchange -b 01/01/2000 -e 01/01/2036 "%~dp0%1.cer"

if "%2" == "root" (
 echo.
 echo WARNING: A TEST CERTIFICATE HAS BEEN ADDED TO THE TRUSTED ROOT 
 echo CERTIFICATION AUTHORITY STORE. FOR SECURITY REASONS, PLEASE REMEMBER 
 echo TO REMOVE THAT CERTIFICATE AFTER YOU FINISH RUNNING THE SAMPLES. YOU
 echo CAN DO SO BY RUNNING CLEANUP.BAT.  
 echo. 
) 

if "%2" == "trustedpeople" (
 echo.
 echo WARNING: A TEST CERTIFICATE HAS BEEN ADDED TO THE TRUSTED PEOPLE 
 echo STORE. FOR SECURITY REASONS, PLEASE REMEMBER TO REMOVE THAT CERTIFICATE 
 echo AFTER YOU FINISH RUNNING THE SAMPLES. YOU CAN DO SO BY RUNNING CLEANUP.BAT.  
 echo. 
)

certutil -addstore %2 "%~dp0%1.cer"

call "%~dp0SetCertHashFromFile.bat" %1

@if "%CERTHASH%" =="" (
   @echo usage: failed to generate cert hash
   @goto :end
)

:doneHash

set KEYCONTAINER=

for /f "tokens=4 usebackq" %%i in ( `certutil -store my %CERTHASH% ^| findstr /c:"Unique container name"`) do (
   set KEYCONTAINER=%%i
)

@if "%KEYCONTAINER%" =="" (
   for /f "tokens=* usebackq" %%v in (`certutil -v -store my %CERTHASH% ^| findstr "[0-9a-fA-F].*_[0-9a-fA-F].*-[0-9a-fA-F].*[0-9a-fA-F]-[0-9a-fA-F].*[0-9a-fA-F]-[0-9a-fA-F].*[0-9a-fA-F]-[0-9a-fA-F].*[0-9a-fA-F]"`) do (
       set KEYCONTAINER=%%v
   )
)

pushd "%ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\RSA\MachineKeys"
cacls %KEYCONTAINER% /e /g "network service":R
popd

:end
